#include "sensorsetting.h"
#include "ui_sensorsetting.h"
#include "showdata.h"
#include "qmqttsen.h"
#include "mysqlqt.h"
#include <qdebug.h>
#include <QStringList>
#include "sensordata.h"
SensorSetting::SensorSetting(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SensorSetting)
{
    ui->setupUi(this);

}

SensorSetting::~SensorSetting()
{
    delete ui;
}

void SensorSetting::ShowEquiInf()
{
    
}

void SensorSetting::AddEquiToMap(QString key, SensorData *sen)
{
    SensorMap->insert(std::make_pair(key,sen));
}

SensorData *SensorSetting::GetEuqiInf(QString key)
{
    if(SensorMap->count(key))
    {
       SensorData* sen = SensorMap->at(key);
       return sen;
    }
    else
    {
        return NULL;
    }

}

void SensorSetting::on_actionSetting_triggered()
{
    QmqttSen* sen = new QmqttSen();
    sen->show();
}


void SensorSetting::on_actionShhow_triggered()
{
    ShowData* data = new ShowData();
    data->show();
}


void SensorSetting::on_AddBut_clicked()
{
    QString EquiName = ui->NameCom->currentText();
    QString ManFact = ui->FactLine->text().trimmed();
    QString ModerId = ui->ModerLine->text().trimmed();
    QString Ragner = ui->RangeLine->text().trimmed();
    QString Signal = "";
    if(ui->DigNumBut->isChecked())
    {
        Signal = ui->DigNumBut->text().trimmed();
    }
    if(ui->AnalNumBut->isChecked())
    {
        Signal = ui->AnalNumBut->text().trimmed();
    }
    // Cache
    SensorData* Sendata = new SensorData(EquiName,ManFact,ModerId,Ragner,Signal);
    AddEquiToMap(ModerId,Sendata);
    // Mysql
    MySqlQt sql = MySqlQt();
    QSqlDatabase db = sql.db;
    sql.ConnectSql(db);
    sql.InsertEquInf(db,Sendata->Name,Sendata->ManFact,Sendata->ModerID,Sendata->Ranger,Sendata->Signal);
}


void SensorSetting::on_SelectEquiBut_clicked()
{
    qDebug() << "on_SelectEquiBut_clicked";
    SensorData* sen1 = new SensorData();
    QString Id = ui->ModeIdLine->text().trimmed();
    sen1 = GetEuqiInf(Id);
    if(sen1 == nullptr)
    {
        MySqlQt sql = MySqlQt();
        QSqlDatabase db = sql.db;
        sql.ConnectSql(db);
        sen1 = sql.SelectEquiById(db,Id);
        ui->InfTabl->setItem(0,0,new QTableWidgetItem(sen1->Name));
        ui->InfTabl->setItem(0,1,new QTableWidgetItem(sen1->ManFact));
        ui->InfTabl->setItem(0,2,new QTableWidgetItem(sen1->ModerID));
        ui->InfTabl->setItem(0,3,new QTableWidgetItem(sen1->Ranger));
        ui->InfTabl->setItem(0,4,new QTableWidgetItem(sen1->Signal));

    }
    else
    {
        ui->InfTabl->setItem(0,0,new QTableWidgetItem(sen1->Name));
        ui->InfTabl->setItem(0,1,new QTableWidgetItem(sen1->ManFact));
        ui->InfTabl->setItem(0,2,new QTableWidgetItem(sen1->ModerID));
        ui->InfTabl->setItem(0,3,new QTableWidgetItem(sen1->Ranger));
        ui->InfTabl->setItem(0,4,new QTableWidgetItem(sen1->Signal));
    }
}

